<template>
  <view class="my-container">
    <!-- 顶部个人信息卡片 -->
    <view class="user-card">
      <view class="avatar-section" @tap="handleChangeAvatar">
        <image 
          class="avatar" 
          :src="userInfo.avatarHash ? (request.baseURL + '/api/avatar/' + userInfo.avatarHash) : '/static/images/default-avatar.png'"
          mode="aspectFill"
        />
        <view class="change-avatar">更换头像</view>
      </view>
      <view class="user-info">
        <text class="nickname">{{ userInfo.realName || userInfo.nickname || userInfo.username }}</text>
        <text class="phone">{{ formatPhone(userInfo.phone) }}</text>
      </view>
    </view>

    <!-- 年度工资统计卡片 -->
    <view class="stat-card">
      <view class="stat-header">
        <text class="title">今年工资统计</text>
        <text class="subtitle">(自春节起)</text>
      </view>
      <view class="stat-content">
        <text class="amount">¥{{ yearSalary }}</text>
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="menu-list">
      <view class="menu-group">
        <view class="menu-item" @tap="handleViewAttendance">
          <text class="iconfont">📅</text>
          <text class="title">考勤记录</text>
          <text class="iconfont arrow">></text>
        </view>
        <view class="menu-item" @tap="handleCancelAttendance">
          <text class="iconfont">❌</text>
          <text class="title">取消今日签到</text>
          <text class="iconfont arrow">></text>
        </view>
      </view>

      <view class="menu-group">
        <view class="menu-item" @tap="handleChangePassword">
          <text class="iconfont">🔒</text>
          <text class="title">修改密码</text>
          <text class="iconfont arrow">></text>
        </view>
        <view class="menu-item" @tap="handleLogout">
          <text class="iconfont">🚪</text>
          <text class="title">退出登录</text>
          <text class="iconfont arrow">></text>
        </view>
      </view>
    </view>

    <!-- 头像裁剪弹窗 -->
    <uni-popup ref="avatarPopup" type="bottom">
      <view class="avatar-popup">
        <view class="popup-header">
          <text class="title">更换头像</text>
          <text class="close" @tap="closeAvatarPopup">×</text>
        </view>
        <view class="popup-content">
          <image-cropper
            v-if="showCropper"
            :src="tempFilePath"
            @confirm="handleCropConfirm"
            @cancel="handleCropCancel"
          />
        </view>
      </view>
    </uni-popup>

    <!-- 修改密码弹窗 -->
    <uni-popup ref="passwordPopup" type="center">
      <view class="password-popup">
        <view class="popup-header">
          <text class="title">修改密码</text>
          <text class="close" @tap="closePasswordPopup">×</text>
        </view>
        <view class="popup-content">
          <input 
            type="password"
            v-model="passwordForm.oldPassword"
            placeholder="请输入原密码"
            class="input"
          />
          <input 
            type="password"
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
            class="input"
          />
          <input 
            type="password"
            v-model="passwordForm.confirmPassword"
            placeholder="请确认新密码"
            class="input"
          />
        </view>
        <view class="popup-footer">
          <button 
            class="confirm-btn"
            :loading="submitting"
            @tap="handlePasswordSubmit"
          >
            确认修改
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import user from '@/api/user'
import attendance from '@/api/attendance'
import salary from '@/api/salary'
import dayjs from 'dayjs'
import request from '@/utils/request'

// 状态
const userInfo = ref({})
const yearSalary = ref(0)
const submitting = ref(false)
const showCropper = ref(false)
const tempFilePath = ref('')

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// popup引用
const avatarPopup = ref(null)
const passwordPopup = ref(null)

// 获取用户信息
async function fetchUserInfo() {
  try {
    const info = await user.getInfo()
    userInfo.value = info
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取年度工资统计
async function fetchYearSalary() {
  try {
    // 获取春节日期
    const now = dayjs()
    const currentYear = now.year()
    // 农历新年一般在1月下旬或2月上旬，这里简单取2月1日
    const springFestival = dayjs(`${currentYear}-02-01`)
    
    // 如果当前日期在2月1日之前，使用上一年的2月1日
    const startDate = now.isBefore(springFestival) ? 
      dayjs(`${currentYear - 1}-02-01`) : 
      springFestival

    const data = await salary.getSalaryStats({
      startDate: startDate.format('YYYY-MM-DD'),
      endDate: now.format('YYYY-MM-DD')
    })
    yearSalary.value = data.totalAmount || 0
  } catch (error) {
    console.error('获取年度工资失败:', error)
  }
}

// 格式化手机号
function formatPhone(phone) {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 更换头像
async function handleChangeAvatar() {
  try {
    console.log('开始选择图片')
    // 选择图片
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    
    console.log('选择图片结果:', res)
    
    // 检查文件大小（限制为2MB）
    const maxSize = 2 * 1024 * 1024 // 2MB
    if (res.tempFiles[0].size > maxSize) {
      uni.showToast({
        title: '图片大小不能超过2MB',
        icon: 'none'
      })
      return
    }

    console.log('开始上传图片, 临时路径:', res.tempFilePaths[0])
    // 直接上传图片
    const avatarHash = await user.updateAvatar(res.tempFilePaths[0])
    console.log('上传成功,返回的hash:', avatarHash)
    
    // 更新用户信息中的头像哈希值
    userInfo.value.avatarHash = avatarHash
    console.log('更新后的用户信息:', userInfo.value)
    
    // 更新本地存储的用户信息
    uni.setStorageSync('userInfo', JSON.stringify(userInfo.value))
    
    uni.showToast({
      title: '头像更新成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('头像更新失败:', error)
    uni.showToast({
      title: error.message || '头像更新失败',
      icon: 'none'
    })
  }
}

// 处理裁剪确认
async function handleCropConfirm(event) {
  try {
    submitting.value = true
    const { path } = event
    await user.updateAvatar(path)
    
    uni.showToast({
      title: '更换头像成功',
      icon: 'success'
    })
    
    // 重新获取用户信息
    await fetchUserInfo()
    closeAvatarPopup()
  } catch (error) {
    uni.showToast({
      title: '更换头像失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 处理裁剪取消
function handleCropCancel() {
  closeAvatarPopup()
}

// 关闭头像弹窗
function closeAvatarPopup() {
  avatarPopup.value.close()
  showCropper.value = false
  tempFilePath.value = ''
}

// 查看考勤记录
function handleViewAttendance() {
  uni.navigateTo({
    url: '/pages/attendance/index'
  })
}

// 取消今日签到
async function handleCancelAttendance() {
  try {
    // 先获取今日考勤记录
    const todayRecord = await attendance.getTodayAttendance()
    if (!todayRecord) {
      uni.showToast({
        title: '今日未签到',
        icon: 'none'
      })
      return
    }
    
    // 取消今日签到，传入记录id
    await attendance.cancelToday(todayRecord.id)
    
    uni.showToast({
      title: '取消签到成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: error.message || '取消签到失败',
      icon: 'none'
    })
  }
}

// 修改密码
function handleChangePassword() {
  passwordPopup.value.open()
}

// 处理密码修改提交
async function handlePasswordSubmit() {
  if (!passwordForm.value.oldPassword) {
    uni.showToast({
      title: '请输入原密码',
      icon: 'none'
    })
    return
  }
  if (!passwordForm.value.newPassword) {
    uni.showToast({
      title: '请输入新密码',
      icon: 'none'
    })
    return
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    })
    return
  }

  try {
    submitting.value = true
    await user.changePassword(passwordForm.value)
    
    uni.showToast({
      title: '修改密码成功',
      icon: 'success'
    })
    
    closePasswordPopup()
    // 清空表单
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    uni.showToast({
      title: error.message || '修改密码失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 关闭密码弹窗
function closePasswordPopup() {
  passwordPopup.value.close()
}

// 退出登录
function handleLogout() {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await user.logout()
          // 清除本地存储
          uni.clearStorageSync()
          // 跳转到登录页
          uni.reLaunch({
            url: '/pages/login/index'
          })
        } catch (error) {
          console.error('退出登录失败:', error)
        }
      }
    }
  })
}

// 页面加载
onMounted(() => {
  fetchUserInfo()
  fetchYearSalary()
})

// 每次显示页面时刷新数据
onShow(() => {
  fetchUserInfo()
  fetchYearSalary()
})
</script>

<style lang="scss">
.my-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: env(safe-area-inset-bottom);
  
  .user-card {
    background: linear-gradient(135deg, #1296db, #6bc6ff);
    padding: 40rpx 30rpx;
    display: flex;
    align-items: center;
    color: #fff;
    
    .avatar-section {
      position: relative;
      margin-right: 30rpx;
      
      .avatar {
        width: 120rpx;
        height: 120rpx;
        border-radius: 60rpx;
        border: 4rpx solid rgba(255, 255, 255, 0.4);
      }
      
      .change-avatar {
        position: absolute;
        bottom: -20rpx;
        left: 50%;
        transform: translateX(-50%);
        font-size: 20rpx;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
      }
    }
    
    .user-info {
      flex: 1;
      
      .nickname {
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
        display: block;
      }
      
      .phone {
        font-size: 24rpx;
        opacity: 0.8;
      }
    }
  }
  
  .stat-card {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 20rpx;
    padding: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .stat-header {
      margin-bottom: 20rpx;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .subtitle {
        font-size: 24rpx;
        color: #999;
        margin-left: 12rpx;
      }
    }
    
    .stat-content {
      .amount {
        font-size: 48rpx;
        font-weight: bold;
        color: #1296db;
      }
    }
  }
  
  .menu-list {
    margin: 20rpx;
    
    .menu-group {
      background-color: #fff;
      border-radius: 20rpx;
      margin-bottom: 20rpx;
      overflow: hidden;
      box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
      
      .menu-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:active {
          background-color: #f9f9f9;
        }
        
        .iconfont {
          font-size: 40rpx;
          margin-right: 20rpx;
          
          &.arrow {
            margin-right: 0;
            margin-left: auto;
            color: #999;
            font-size: 32rpx;
          }
        }
        
        .title {
          font-size: 30rpx;
          color: #333;
        }
      }
    }
  }
  
  .avatar-popup {
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    overflow: hidden;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .close {
        font-size: 40rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .popup-content {
      padding: 30rpx;
    }
  }
  
  .password-popup {
    background-color: #fff;
    border-radius: 20rpx;
    width: 600rpx;
    
    .popup-header {
      padding: 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
      }
      
      .close {
        font-size: 40rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .popup-content {
      padding: 30rpx;
      
      .input {
        height: 88rpx;
        background-color: #f8f8f8;
        border-radius: 12rpx;
        padding: 0 20rpx;
        margin-bottom: 20rpx;
        font-size: 28rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
    
    .popup-footer {
      padding: 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      .confirm-btn {
        background: linear-gradient(135deg, #1296db, #6bc6ff);
        color: #fff;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        font-weight: bold;
        
        &[disabled] {
          opacity: 0.7;
        }
      }
    }
  }
}
</style> 